﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Services.Client;
using BusinessObjects;
using TcpServer.GreenWorldEntitiesService;

namespace YourWorldServer
{
    public class RegionObjectsRepository
    {
        private GreenWorldEntities entities;

        private static RegionObjectsRepository instance;

        private RegionObjectsRepository()
        {
            this.RegionObjects = new Dictionary<int, RegionObject>();
            this.RubbishIds = new List<int>();
            this.entities = new GreenWorldEntities( new Uri( ServiceUrl, UriKind.Absolute ) );
        }

        public static string ServiceUrl
        {
            get;
            set;
        }

        public static RegionObjectsRepository Instance
        {
            get
            {
                if ( instance == null )
                    instance = new RegionObjectsRepository();

                return instance;
            }
        }

        public void Initialize()
        {
            this.LoadRegionObjects();
        }

        public Dictionary<int, RegionObject> RegionObjects
        {
            get;
            private set;
        }

        public List<int> RubbishIds
        {
            get;
            set;
        }

        public RegionObject GetRegionObject( int id )
        {
            if ( this.RegionObjects.ContainsKey( id ) == false )
                return null;

            return this.RegionObjects[id];
        }

        public GameObject GetRubbinshForId( int id )
        {
            RegionObject regionObject = this.GetRegionObject( id );

            if ( regionObject == null || regionObject.MaterialTypeId == Consts.UnSpecifiedBinId )
                return null;

            GameObject rubbish = new GameObject()
            {
                Id = regionObject.Id,
                Type = ObjectsType.Rubbish
            };

            return rubbish;
        }

        private void LoadRegionObjects()
        {
            var regionObjects = ( from r in entities.RegionObjects select r ) as DataServiceQuery<RegionObject>;
            regionObjects.BeginExecute( new AsyncCallback( this.LoadRegionObjectsCompleted ), regionObjects );
        }

        private void LoadRegionObjectsCompleted( IAsyncResult state )
        {
            var regionObjects = state.AsyncState as DataServiceQuery<RegionObject>;

            List<RegionObject> ros = regionObjects.EndExecute( state ).ToList();

            foreach ( RegionObject ro in ros )
            {
                this.RegionObjects.Add( ro.Id, ro );

                if ( ro.Template == RegionObjectTypes.Rubbish.ToString() )
                    this.RubbishIds.Add( ro.Id );
            }
        }
    }
}
